﻿#region << 文件说明 >>

/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.WebApi
 * 唯一标识：4d937610-3f37-4419-8025-79740ffd8492
 * 文件名：VampirewalWebApiBootStartup
 *
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2023/10/7 13:55:16
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

#endregion << 文件说明 >>

namespace Vampirewal.Core.WebApi;

/// <summary>
/// 启动WebApi的BootStartup
/// </summary>
public abstract class VampirewalWebApiBootStartup : VampirewalBootStartUp, IVampirewalBootStartUp
{
    /// <summary>
    /// 构建BootStartup并启动
    /// <para><typeparamref name="框架已自动调用请勿重复调用"/></para>
    /// </summary>
    /// <exception cref="BootStartUpException"></exception>
    public override void BuildBootStartUp(string[] args)
    {
        if (IsStart)
        {
            throw new BootStartUpException("请勿重复调用！");
        }

        GetStartArgs(args);

        RegisterService(Collection);

        RegisterAll(Collection);

        SetServiceProvider(Collection.BuildServiceProvider());

        VampirewalCoreContext.GetInstance().SetService(Services);

        StartHttpListener();

        WindowsManager.GetInstance().OpenWindow(FirstViewKey, IsMainWindow: true);

        IsStart = true;
    }

    private HttpListener httpListener { get; set; }

    private VampirewalMiddlewarePipeline middlewareContainer { get; set; }

    private void StartHttpListener()
    {
        try
        {
            var config = Services.GetService<VampirewalCoreWebApiConfig>();

            if (!config.IsStartWebApi)
            {
                return;
            }

            var middlewares = Services.GetServices<IVampirewalMiddleware>().ToList();

            middlewareContainer = new VampirewalMiddlewarePipeline(middlewares);

            httpListener = new HttpListener();

            httpListener.Prefixes.Add(config.Url);

            

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private async void GetContextCallBack(IAsyncResult result)
    {
        var http = result.AsyncState as HttpListener;

        httpListener.BeginGetContext(GetContextCallBack, httpListener);

        //获取监听的上下文
        var context = http.EndGetContext(result);

        //执行中间件
        await middlewareContainer.InvokeAsync(context);

        //释放并将数据返回客户端
        context.Response.Close();
    }

    public override void OnAppRun(bool IsRun)
    {
        httpListener.Start();

        httpListener.BeginGetContext(GetContextCallBack, httpListener);
    }

    public override void OnAppExit(bool IsRun)
    {
        httpListener.Stop();
    }
}